import { ComponentClass } from 'react'
import { connect } from '@tarojs/redux'
import Taro, { Component } from '@tarojs/taro'
import { View, ScrollView, Image } from '@tarojs/components'
import { SDPopup, SDQuantity } from 'sudao-ui'
import SDUtils from 'sudao-utils'

import PageProps from '../../redux'
import { login, logout, setShopCart } from '../../redux/actions'

import SDButton from '../../comps/sd-button'

import IconCancel from '../../images/ic_cancel.png'

import './index.less'

type PageOwnProps = {
  onSelect?: (skuList: any[]) => void,
  onDismiss?: () => void
}

type PageState = {
  loading: boolean,
  productData: any,
  skuList: any[],
  btnIsLoading: boolean,
  totalCount: number,
  totalPrice: number,
  silverPriceData: any,
  locked: boolean
}

interface SKUPicker {
  props: PageProps & PageOwnProps
}

@connect(({userState, cartState}) => ({
  userState,
  cartState
}), (dispatch) => ({
  login(userInfo) {
    dispatch(login(userInfo))
  },
  logout() {
    dispatch(logout())
  },
  setShopCart(cartData) {
    dispatch(setShopCart(cartData))
  }
}))
class SKUPicker extends Component<{}, PageState> {

  constructor (args) {
    super(args)
    this.state = {
      loading: true,
      productData: {},
      skuList: [],
      btnIsLoading: false,
      totalCount: 0,
      totalPrice: 0,
      silverPriceData: {},
      locked: false
    }
  }

  skuRequestTask: any | undefined = undefined
  goodsRequestTask: any | undefined = undefined
  silverPriceTask: any | undefined = undefined

  render () {
    const { loading, productData, skuList, btnIsLoading, totalCount, totalPrice, locked, silverPriceData } = this.state
    return (
      <SDPopup ref='compsPupup' locked={locked}>
        {
          loading ? (
            <View className="main-loading">
              <View className="section-header border-bottom_1px">
                <Image className="img-icon placeholder" src='' mode='aspectFill' lazyLoad></Image>
                <View className="right">
                  <View className="title placeholder"></View>
                  <View className="sub-title placeholder"></View>
                  <View className="sub-title sub-title_small placeholder"></View>
                </View>
                <View className="btn-close" onClick={this.closePopup}>
                  <Image className="icon" src={IconCancel}></Image>
                </View>
              </View>
              <View className='loading-pannel'>
                <View className='weui-loading'></View>
                <View>正在加载中...</View>
              </View>
            </View>
            ) : (
            <View className="main-content">
              <View className="section-header border-bottom_1px">
                <Image className="img-icon" src={SDUtils.processImageURL(productData.coverImage || '', 336)} mode='aspectFill' lazyLoad></Image>
                <View className="right">
                  <View className="title">{productData.name}</View>
                  <View className="sub-title">今日银价：{SDUtils.formatPrice(`${silverPriceData.price || 0}`)}/g</View>
                  <View className="sub-title sub-title_small">工艺费：{SDUtils.formatPrice(`${productData.processFee || 0}`)}/g</View>
                </View>
                <View className="btn-close" onClick={this.dismiss}>
                  <Image className="icon" src={IconCancel}></Image>
                </View>
                <View className="btn-clear" onClick={this.onClearBtnTaped}>
                  <View className="title">清空</View>
                </View>
              </View>
              <ScrollView className="scroll-content" scrollY>
                <View className="inner-content">
                  {
                    skuList.map((item, index) => {
                      return (
                        <View className={`cell-item ${(item.sellStock || 0) < (item.quantity || 0) ? 'cell-item_less' : ''} border-bottom_1px`} key={index}>
                          <View className="left">
                            <View className="title">{item.skuTitle}</View>
                            <View className="bottom">
                              <View className="item">{SDUtils.formatPrice(`${item.calcPrice}`)}</View>
                              <View className="item">吊牌价{SDUtils.formatPrice(`${item.tagPrice || 0}`)}</View>
                              <View className="item">库存:{item.sellStock || 0}</View>
                            </View>
                          </View>
                          <View className="right">
                            <SDQuantity
                              // max={item.sellStock || 0}
                              value={item.quantity || 0}
                              extData={index}
                              onValueChange={this.onQuantityValueChange}
                              onBoundary={this.onQuantityBoundary}
                            />
                          </View>
                        </View>
                      )
                    })
                  }
                </View>
              </ScrollView>
              <View className="section-footer border-top_1px">
                <View className="left">
                  <View className="item">
                    <View className="tips">数量：</View>
                    <View className="title">{totalCount}</View>
                  </View>
                  <View className="item">
                    <View className="tips">合计：</View>
                    <View className="title">{SDUtils.formatPrice(`${totalPrice}`)}</View>
                  </View>
                </View>
                <SDButton height={98} sd-class='right' loading={btnIsLoading} onClick={this.onConfirmBtnTaped}>确定</SDButton>
              </View>
            </View>
          )
        }
      </SDPopup>
    )
  }

  onConfirmBtnTaped = async () => {
    const { btnIsLoading, skuList } = this.state
    if (btnIsLoading) { return }
    if (skuList.length <= 0) {
      return
    }
    await this.setState({
      btnIsLoading: true,
      locked: true
    })
    let paramList: any[] = []
    for (let i = 0; i < skuList.length; i++) {
      let item = skuList[i]
      paramList.push({
        skuId: item.skuId,
        quantity: item.quantity
      })
    }
    //TODO
    // paramList = paramList.filter(item => item.quantity > 0)
    try {
      await SDUtils.doPut('/wxmini/cart/batch', paramList)
      const resp = await SDUtils.doGet('/wxmini/cart')
      this.props.setShopCart({
        cartList: resp.cartItemVos || [],
        invalidCartList: []
      })
      SDUtils.showMsg('已成功加入购物车')
      this.props.onSelect && this.props.onSelect(skuList)
      this.dismiss()
    } catch (e) {
      SDUtils.showMsg(e)
    } finally {
      this.setState({
        btnIsLoading: false,
        locked: false
      })
    }
  }

  onClearBtnTaped = () => {
    let {skuList} = this.state
    skuList = skuList.map(item => {
      item.quantity = 0
      return item
    })
    this.setState({
      skuList: skuList
    })
  }

  fetchData = async (productId: any) => {
    let productData: any = {}
    let skuList: any[] = []
    let loading = true
    let silverPriceData = {}

    try {
      let skuRequestTask = SDUtils.getAbortToken()
      let goodsRequestTask = SDUtils.getAbortToken()
      let silverPriceTask = SDUtils.getAbortToken()
      this.skuRequestTask = skuRequestTask
      this.goodsRequestTask = goodsRequestTask
      this.silverPriceTask = silverPriceTask
      productData = await SDUtils.doGet(`/wxmini/traderProduct/${productId}`, {}, goodsRequestTask)
      skuList = await SDUtils.doGet(`/wxmini/traderProduct/${productId}/spec`, {}, skuRequestTask)
      silverPriceData = await SDUtils.doGet('/wxmini/silverPrice/newest')
      loading = false
    } catch (e) {
      SDUtils.showMsg(e)
      setTimeout(() => {
        this.dismiss()
      }, 1000)
    } finally {
      this.setState({
        productData: productData,
        skuList: skuList,
        silverPriceData: silverPriceData
      }, () => {
        this.calcPrice(loading)
      })
    }
  }

  calcPrice = (loading: boolean) => {
    let { skuList, productData, silverPriceData } = this.state
    let silverPrice = silverPriceData.price     // 今日银价
    let processFee = productData.processFee || 0
    let unitPrice = silverPrice + processFee

    let minPrice = Number.MAX_SAFE_INTEGER
    let maxPrice = 0

    let totalCount = 0
    let totalPrice = 0

    for (let i = 0; i < skuList.length; i++) {
      let skuItem = skuList[i]
      // SKU计算价格
      skuItem.calcPrice = unitPrice * (skuItem.weight || 0)
      let skuSpecs = skuItem.specItems || []
      let skuTitle = skuSpecs.map(item => item.attrValue).join(' ')
      minPrice = Math.min(skuItem.calcPrice, minPrice)
      maxPrice = Math.max(skuItem.calcPrice, maxPrice)
      skuItem.skuTitle = skuTitle

      totalCount += skuItem.quantity || 0
      totalPrice += (skuItem.quantity || 0) * (skuItem.calcPrice || 0)
    }
    let priceRange = SDUtils.formatPrice(`${minPrice}`)
    if (minPrice < maxPrice) {
      priceRange = `${SDUtils.formatPrice(`${minPrice}`)}-${SDUtils.formatPrice(`${maxPrice}`)}`
    }

    productData.priceRange = priceRange
    this.setState({
      loading: loading,
      productData: productData,
      skuList: skuList,
      totalPrice: totalPrice,
      totalCount: totalCount
    })
  }

  onQuantityValueChange = (value: string, extData: number) => {
    let currentQuantiy = parseInt(value)
    currentQuantiy = isNaN(currentQuantiy) ? 0 : currentQuantiy
    let { skuList } = this.state
    skuList[extData].quantity = currentQuantiy
    this.setState({
      skuList: skuList
    }, () => {
      this.calcPrice(false)
    })
  }

  onQuantityBoundary = (_: string, type: 'plus' | 'minus') => {
    if (type == 'plus') {
      SDUtils.showMsg('库存不足')
    } else {
      SDUtils.showMsg('数量不能少于0')
    }
  }

  show = (productId: any) => {
    this.fetchData(productId)
    this.refs.compsPupup && this.refs.compsPupup.show()
  }

  closePopup = () => {
    if (this.state.btnIsLoading) {
      return
    }
    this.dismiss()
  }

  dismiss = () => {
    this.refs.compsPupup && this.refs.compsPupup.dismiss()
    this.goodsRequestTask && this.goodsRequestTask.abort()
    this.silverPriceTask && this.silverPriceTask.abort()
    this.skuRequestTask && this.skuRequestTask.abort()

    this.setState({
      loading: true,
      silverPriceData: {},
      skuList: []
    })
  }
}

export default SKUPicker as ComponentClass<PageOwnProps, PageState>
